﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using BP.OA;
namespace CCOA.App.News
{
    public partial class NewsEdit : System.Web.UI.Page
    {
        #region //1.公共接口(Public Interface)
        //权限控制
        private string FuncNo = null;
        private string CurUserNo
        {
            get { return BP.Web.WebUser.No; }
        }
        private void Alert(string msg)
        {
            BP.OA.Debug.Alert(this, msg);
        }
        private DataTable GetArticleCataogry()
        {
            string sSql = "Select No,Name from OA_ArticleCatagory order by No";
            return BP.DA.DBAccess.RunSQLReturnTable(sSql);
        }
        private int rId
        {
            get { return Convert.ToInt32(Request.QueryString["ID"]); }
        }
        private int News_Update(int oid,String FK_ArticleCatagory, String Title, String KeyWords, String Doc, String ArticleSource,String AttachFile)
        {
            /*
            BP.OA.Article arNew = new BP.OA.Article(oid);
            arNew.AddTime = DateTime.Now;
            arNew.FK_UserNo = curUserNo;
            arNew.FK_ArticleCatagory = ArticleCatagory;
            arNew.Title = Title;
            arNew.KeyWords = KeyWords;
            arNew.Doc = Doc;            
            return arNew.Update();
             * */
            string sql = String.Format("UPDATE OA_Article SET FK_ArticleCatagory ='{1}' ,Title ='{2}' ,KeyWords ='{3}' ,Doc = '{4}',ArticleSource='{5}',AttachFile='{6}'   WHERE OID={0}"
                              , oid, FK_ArticleCatagory, Title.Replace("'", "''"), KeyWords.Replace("'", "''"), Doc.Replace("'", "''"), ArticleSource.Replace("'", "''"),AttachFile);
            return BP.DA.DBAccess.RunSQL(sql);
        }
        /// <summary>
        /// 获取路径函数
        /// </summary>
        /// <returns></returns>
        private string GetAttachPathName()
        {
            string dir = String.Format("/DataUser/UploadFile/Article/{0:yyyyMMdd}", DateTime.Now);
            return dir;
        }
        /// <summary>
        /// 获取新文件名函数
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string GetAttachFileName(string fileName)
        {
            string f = System.IO.Path.GetFileNameWithoutExtension(fileName);
            string ext = System.IO.Path.GetExtension(fileName);
            string newFileName = String.Format("{0}_{1:yyyyMMddHHmmss}{2}", f, DateTime.Now, ext);
            return newFileName;
        }
        /// <summary>
        /// 根据存储路径获取老文件名，必须是存储路径中包含老文件名才可。
        /// </summary>
        /// <param name="savePath"></param>
        /// <returns></returns>
        private string GetAttachOldFileName(string savePath)
        {
            string saveFullPath = Server.MapPath(savePath);
            //文件不存在直接反回空
            if (!System.IO.File.Exists(saveFullPath)) return "";

            String attachFile = System.IO.Path.GetFileName(saveFullPath);
            String ext = System.IO.Path.GetExtension(saveFullPath);
            int index = attachFile.LastIndexOf('_');
            string oldName = index == -1 ? attachFile : attachFile.Substring(0, index);
            //String[] arr_attachFile = attachFile.Split('_');
            return String.Format("{0}{1}", oldName, ext);
        }

        public string GetAllAttachStr(string savePath, string splitter, string linkFormat)
        {
            if (splitter == null) splitter = ""; //"&nbsp;&nbsp;";
            if (String.IsNullOrEmpty(linkFormat)) linkFormat = "<a href='{1}'>{0}</a>";
            StringBuilder sb = new StringBuilder();
            String[] attachFiles = savePath.Split(new String[] { ";", ",", "|" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (String attachFile in attachFiles)
            {
                if (sb.Length > 0) sb.Append(splitter);
                sb.AppendFormat(linkFormat
                    , this.GetAttachOldFileName(attachFile)
                    , attachFile);
            }
            return sb.ToString();
        }
        #endregion

        #region //2.页面装载(Page Load)
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                BP.OA.UI.Dict.BindListCtrl(this.GetArticleCataogry(), this.ui_ArticleCatagory, "Name", "No", null, null, null);
                this.LoadData();
            }
        }
        private void LoadData()
        {
            Article arEdit = new Article(this.rId);            
            //arEdit.RetrieveFromDBSources();
            this.ui_ArticleCatagory.SelectedValue = arEdit.FK_ArticleCatagory;
            this.ui_Title.Text = arEdit.Title;
            this.ui_KeyWords.Text = arEdit.KeyWords;
            this.ui_Doc.Text = arEdit.Doc;
            this.ui_ArticleSource.Text = arEdit.ArticleSource;

            String attachPath = arEdit.AttachFile;
            this.hfAttachFiles.Value = attachPath;
            this.liAttachFiles.Text = this.GetAllAttachStr(attachPath, " ", "<div class='multi-old-div'><a href='#' class='multi-old-remove'>x</a>&nbsp;<a class='multi-old-url' href='{1}'>{0}</a></div>");
        }
        #endregion
        #region //3.页面事件(Page Event)
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //0.用户权限
            if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            //1.获取用户变量
            String curUserNo = BP.Web.WebUser.No;
            String ArticleCatagory = this.ui_ArticleCatagory.SelectedValue;
            String Title = this.ui_Title.Text;
            String KeyWords = this.ui_KeyWords.Text;
            String ArticleSource = this.ui_ArticleSource.Text;
            String Doc = this.ui_Doc.Text;
            String AttachFile = this.hfAttachFiles.Value;
            //2.数据验证
            StringBuilder sbErr = new StringBuilder();
            if (String.IsNullOrEmpty(Title))
            {
                sbErr.AppendFormat("{0}\r\n","文章标题不能为空！");
            }
            if (String.IsNullOrEmpty(Doc))
            {
                sbErr.AppendFormat("{0}\r\n", "文章内容不能为空！");
            }
            if (sbErr.Length > 0)
            {
                this.Alert(sbErr.ToString());
                return;
            }
            //3.数据处理
            
            //3.1.文件删除
            if (!String.IsNullOrEmpty(AttachFile))
            {
                StringBuilder sbOldFile = new StringBuilder();
                String[] oldFiles = AttachFile.Split(new String[] { ",", ";", "|" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String oldFile in oldFiles)
                {
                    if (oldFile.StartsWith("#"))
                    {
                        System.IO.File.Delete(Server.MapPath(oldFile.Substring(1)));
                    }
                    else
                    {
                        sbOldFile.AppendFormat("{0};", oldFile);
                    }
                }
                AttachFile = sbOldFile.ToString();
            }
            //3.2.文件夹检测
            string dir = this.GetAttachPathName();
            if (!System.IO.Directory.Exists(Server.MapPath(dir)))
                System.IO.Directory.CreateDirectory(Server.MapPath(dir));

            //3.3.多文件上传
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hpf.ContentLength > 0)
                {
                    string newFileName = this.GetAttachFileName(hpf.FileName);

                    string path = String.Format("{0}/{1}", dir, newFileName);
                    //string filePath = this.FileUpload1.PostedFile.FileName;
                    try
                    {
                        hpf.SaveAs(Server.MapPath(path));
                        AttachFile += String.Format("{0};", path);
                        //System.IO.File.Delete(Server.MapPath(hlFile.NavigateUrl));
                    }
                    catch
                    {
                        ;
                    }
                }
            }
            bool blnOpe = false;      
            blnOpe = this.News_Update(this.rId,ArticleCatagory,Title,KeyWords,Doc,ArticleSource,AttachFile)==1;
            //4.统计/日志
            //5.提示处理信息
            if (blnOpe)
            {
                //this.Alert("修改文章成功");
                //this.Response.Redirect("NewsList.aspx");
                BP.OA.Debug.Confirm(this, "成功修改新闻内容！返回新闻管理？", "NewsList.aspx", "");
            }
            else
                this.Alert("修改文章失败");
        }
        #endregion
    }
}